package com.example.demo.controller;

import com.example.demo.service.LeaveApprovalService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假审批流程控制器
 */
@RestController
@RequestMapping("/api/leave-approval")
public class LeaveApprovalController {

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private LeaveApprovalService leaveApprovalService;

    /**
     * 启动请假审批流程
     */
    @PostMapping("/start")
    public Map<String, Object> startLeaveApprovalProcess(@RequestBody Map<String, Object> request) {
        try {
            // 准备流程变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("applicant", request.get("applicant"));
            variables.put("leaveType", request.get("leaveType"));
            variables.put("leaveDays", request.get("leaveDays"));
            variables.put("reason", request.get("reason"));
            variables.put("applyTime", request.get("applyTime"));
            
            // 设置审批人（实际项目中应该从用户服务获取）
            variables.put("directManager", "manager001");
            variables.put("hrManager", "hr001");
            variables.put("departmentManager", "dept001");

            // 启动流程实例
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                "employeeLeaveApproval", variables);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("processInstanceId", processInstance.getId());
            response.put("message", "请假审批流程已启动");

            return response;

        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return response;
        }
    }

    /**
     * 获取待办任务列表
     */
    @GetMapping("/tasks")
    public Map<String, Object> getTasks(@RequestParam(required = false) String assignee) {
        try {
            List<Task> tasks;
            if (assignee != null) {
                tasks = taskService.createTaskQuery()
                    .taskAssignee(assignee)
                    .processDefinitionKey("employeeLeaveApproval")
                    .list();
            } else {
                tasks = taskService.createTaskQuery()
                    .processDefinitionKey("employeeLeaveApproval")
                    .list();
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("tasks", tasks);
            response.put("count", tasks.size());

            return response;

        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return response;
        }
    }

    /**
     * 完成任务
     */
    @PostMapping("/complete/{taskId}")
    public Map<String, Object> completeTask(
            @PathVariable String taskId,
            @RequestBody Map<String, Object> request) {
        try {
            // 准备任务变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("approved", request.get("approved"));
            variables.put("comment", request.get("comment"));

            // 完成任务
            taskService.complete(taskId, variables);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "任务已完成");

            return response;

        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return response;
        }
    }

    /**
     * 获取流程实例详情
     */
    @GetMapping("/process/{processInstanceId}")
    public Map<String, Object> getProcessInstance(@PathVariable String processInstanceId) {
        try {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

            if (processInstance == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("error", "流程实例不存在");
                return response;
            }

            // 获取流程变量
            Map<String, Object> variables = runtimeService.getVariables(processInstanceId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("processInstance", processInstance);
            response.put("variables", variables);

            return response;

        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return response;
        }
    }

    /**
     * 测试流程 - 创建示例数据
     */
    @PostMapping("/test")
    public Map<String, Object> testProcess() {
        try {
            // 测试数据1：短期请假
            Map<String, Object> shortLeaveRequest = new HashMap<>();
            shortLeaveRequest.put("applicant", "张三");
            shortLeaveRequest.put("leaveType", "personal");
            shortLeaveRequest.put("leaveDays", 2);
            shortLeaveRequest.put("reason", "个人事务处理");
            shortLeaveRequest.put("applyTime", "2024-01-01T09:00:00");

            // 测试数据2：长期请假
            Map<String, Object> longLeaveRequest = new HashMap<>();
            longLeaveRequest.put("applicant", "李四");
            longLeaveRequest.put("leaveType", "annual");
            longLeaveRequest.put("leaveDays", 7);
            longLeaveRequest.put("reason", "年度休假计划");
            longLeaveRequest.put("applyTime", "2024-01-01T09:00:00");

            // 启动两个测试流程
            Map<String, Object> result1 = startLeaveApprovalProcess(shortLeaveRequest);
            Map<String, Object> result2 = startLeaveApprovalProcess(longLeaveRequest);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("shortLeaveProcess", result1);
            response.put("longLeaveProcess", result2);
            response.put("message", "测试流程已启动");

            return response;

        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return response;
        }
    }
}

